import { Carousel } from './carousel';

class Slider extends Carousel {
  constructor($, options) {
    super($, options);
    // dom 节点
    this.oCarList = this.$dom.find('.car-list');

    // 参数设置
    this.carW = 550;
    this.MAXLEN = this.oCarItems.length;
    this.t = null;

    this.init();
  }

  init() {
    this.addEndPicture();
    this.autoCarousel();
    this.bindClickEvent();
  }

  // 在尾部添加第一张图片
  addEndPicture() {
    // 克隆出来给父节点添加上
    this.oCarList.append(this.oCarItems.eq(0).clone());
  }

  carClick(event) {
    // 兼容处理
    const e = event || window.event;
    const target = e.target || e.srcElement;
    const className = target.className.split(' ')[0];
    let index;
    switch (className) {
      case 'car-button':
        // 左右按钮
        index = target.getAttribute('data-type') === 'prev' ? this.curIndex - 1 : this.curIndex + 1;
        this._setIndex(index);
        break;
      case 'indicator-btn':
        // 小圆点点击
        index = $(target).index();
        this._setIndex(index);
        break;
      default:
        break;
    }
  }

  // 开始轮播
  run() {
    // this._slideAction('next');
    this._setIndex(this.curIndex + 1);
  }

  pageChange(index) {
    this.oCarIndicators.eq(index).addClass('active').siblings('i').removeClass('active');
  }

  _setIndex(index) {
    // console.log(this.curIndex);
    if (index > this.MAXLEN) {
      this.curIndex = 1;
      this._setSlider(this.curIndex, true, 'next');
      this.t = setTimeout(() => {
        this._setSlider(this.curIndex, false);
        clearTimeout(this.t);
      }, 100)
    } else if (index < this.MINLEN) {
      this.curIndex = this.MAXLEN - 1;
      this._setSlider(this.curIndex, true, 'prev');
      this.t = setTimeout(() => {
        this._setSlider(this.curIndex, false);
        clearTimeout(this.t);
      }, 100)
    } else {
      this.curIndex = index;
      this._setSlider(this.curIndex, false);
    }
    this.pageChange(this.curIndex === this.MAXLEN ? 0 : index);
  }

  _setSlider(index, isInitial, dir) {
    // dir：方向，前进还是后退
    let value = isInitial ? (dir === 'prev' ? -this.MAXLEN * this.carW : 0) : -index * this.carW;
    let duration = isInitial ? 'initial' : '0.5s';
    this.oCarList.css({
      'transform': `translate3d(${value}px, 0, 0)`,
      'transition-duration': duration
    });
  }
}

export { Slider };